<template>
  <view>
    <view style="width: 100%;margin-bottom: 20rpx;margin-top: 20rpx">
      <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <image class="avatar" :src="user.avatar" mode="widthFix" ></image>
      </button>

    </view>

    <uni-list style="width: 90%">
      <uni-list-item :clickable="true" title="昵称" showArrow :rightText="user.nickname"
                     @click="turnInput({
                     value:user.nickname,
                     paramName:'user.nickname',
                     title:'更改昵称'
                     })"/>
      <uni-list-item :clickable="true" title="姓名" showArrow :rightText="user.name"
                     @click="turnInput({
                     value:user.name,
                     paramName:'user.name',
                     title:'更改名字'
                     })"/>
      <picker @change="bindPickerChange" value="0" range-key="label" :range="list">
        <uni-list-item :clickable="true" title="性别" showArrow :rightText="user.sexName"/>
      </picker>

      <uni-datetime-picker type="date" v-model="user.birthday">
        <uni-list-item :clickable="true" title="生日" showArrow :rightText="user.birthday"/>
      </uni-datetime-picker>
      <uni-list-item :clickable="true" title="电话" showArrow :rightText="user.phone"
                     @click="turnInput({
                     value:user.phone,
                     paramName:'user.phone',
                     title:'更改电话'
                     })"/>
      <uni-list-item :clickable="true" title="邮箱" showArrow :rightText="user.email"
                     @click="turnInput({
                     value:user.email,
                     paramName:'user.email',
                     title:'更改邮箱'
                     })"/>
      <uni-list-item :clickable="true" title="个人介绍" showArrow :rightText="user.introduction"
                     @click="turnInput({
                     value:user.introduction,
                     paramName:'user.introduction',
                     title:'更改自我介绍'
                     })"/>
      <uni-list-item :clickable="true" title="微信" showArrow :rightText="user.openId?'已绑定':'未绑定'"
                     @click="bindOrRemoveWx"/>

    </uni-list>
  </view>
</template>

<script>
import {UserService} from "../../../../api/user";
import {BASE_URL} from "../../../../api/service";
import {BASE_IMG_URL} from "../../../../api/service";

export default {

  data() {
    return {
      user: uni.getStorageSync('userInfo').userInfo,
      wxCode:"",
      list:[
          {
        label:"男",
        value:1,
      },
        {
          label:"女",
          value:2,
        }
      ]
    }
  },
  created() {
    // console.log(this.user)
  },
  watch:{
    user: {
      handler(newUser, oldUser) {
        // console.log("change",newUser)
        UserService.updateUser(newUser).then(res=>{
          if(res.data.code==0){
            let user=uni.getStorageSync("userInfo");
            user.avatar=this.user.avatar;
            user.nickname=this.user.nickname;
            user.userInfo=this.user;
            uni.setStorageSync('userInfo',user);
          }
        })
      },
      deep: true
    }
  },
  onUnload() {
    let pages = getCurrentPages(); // 当前页面
    let beforePage = pages[pages.length - 2]; // 上一页
    beforePage.$vm.$refs.mine.user = this.user;
    console.log("unload")
  },
  methods: {
    onChooseAvatar(e){
      console.log(e.detail.avatarUrl)
      uni.uploadFile({
        url: BASE_URL + '/erp/system/Attachment/appSaveAttachment', //仅为示例，非真实的接口地址
        header: {
          "Authorization": uni.getStorageSync('token'),
          'Content-Type': 'multipart/form-data'
        },
        filePath: e.detail.avatarUrl,
        name: 'file',
        formData: {
          "associateFormId": this.user.eid,
          "associateFormName": "avatar"
        },
        success: (uploadFileRes) => {
          this.user.avatar=BASE_IMG_URL+JSON.parse(uploadFileRes.data).attachmentAddr
        },
        fail: (e => {
          console.log(e)
        })
      });
    },
    turnInput(data){
      uni.navigateTo({
        url: '/pages/components/MyInput?dispose=' + encodeURIComponent(JSON.stringify(data)),
      })
    },
    bindPickerChange: function(e) {
      let index=e.detail.value;
      // console.log('picker发送选择改变，携带值为', this.list[index])
      this.user.sex=this.list[index].value;
      this.user.sexName=this.list[index].label;
    },
    bindOrRemoveWx(){
      if(this.user.openId){
        this.removeWx();
      }else{
        this.bindWx();
      }
    },
    removeWx(){
      let _this=this
      uni.showModal({
        title: '提示',
        content: '你确定解除微信绑定吗？',
        success: function (res) {
          if (res.confirm) {
            uni.login({
              provider: 'weixin',
              success: (res) => {
                if (res.errMsg == 'login:ok') {
                  UserService.removeWx(res.code,_this.user.eid).then((res) => {
                    //获取到 openid 和 session_k后，自己的逻辑
                    if(res.data.code==0) {
                      uni.showToast({
                        title: '解除成功',
                        icon: 'success',
                        duration: 2000
                      })
                      let user=uni.getStorageSync("userInfo");
                      _this.user.openId=null;
                      user.userInfo=_this.user;
                      uni.setStorageSync('userInfo',user);
                    }else{
                      uni.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }).catch(err => {
                    console.log("err", err)
                  })
                }
              },
            });



          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
    },
    bindWx(){
      let _this=this
      uni.showModal({
        title: '提示',
        content: '是否确定绑定微信?绑定之后可以使用微信一键登录。',
        success: function (res) {
          if (res.confirm) {
            uni.login({
              provider: 'weixin',
              success: (res) => {
                if (res.errMsg == 'login:ok') {
                  UserService.bindWx(res.code,_this.user.eid).then((res) => {
                    //获取到 openid 和 session_k后，自己的逻辑
                    console.log("resDaa-----",res)
                    if(res.data.code==0) {
                      uni.showToast({
                        title: '绑定成功',
                        icon: 'success',
                        duration: 2000
                      })
                      let user=uni.getStorageSync("userInfo");
                      _this.user.openId=res.data.openId;
                      user.userInfo=_this.user;
                      uni.setStorageSync('userInfo',user);
                    }else{
                      uni.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }).catch(err => {
                    console.log("err", err)
                  })
                }
              },
            });



          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
    },
    alterAvatar(){
      uni.chooseImage({
        sourceType: ['album'], //从相册选择
        success: chooseImageRes => {
          console.log('成功', chooseImageRes);
          const tempFilePaths = chooseImageRes.tempFilePaths;
          uni.uploadFile({
            url: BASE_URL + '/erp/system/Attachment/appSaveAttachment', //仅为示例，非真实的接口地址
            header: {
              "Authorization": uni.getStorageSync('token'),
              'Content-Type': 'multipart/form-data'
            },
            filePath: tempFilePaths[0],
            name: 'file',
            formData: {
              "associateFormId": this.user.eid,
              "associateFormName": "avatar"
            },
            success: (uploadFileRes) => {
              this.user.avatar=BASE_IMG_URL+JSON.parse(uploadFileRes.data).attachmentAddr
            },
            fail: (e => {
              console.log(e)
            })
          });
        },
        fail: err => {
          console.log(err.message)
        }
      });
    }

  }
}
</script>

<style>
.avatar {
  width: 120rpx;
  height: 120rpx;
  margin: auto;
  /*display: block;*/
  /*border-radius: 100rpx;*/
  /*border: solid #bbbbbb 1px;*/
}
.avatar-wrapper{
  width: 120rpx;
  height: 120rpx;
  padding: 0!important;
}
</style>
